package com.chinasoftinc.facommon.control.conversation;

import com.chinasoftinc.facommon.utils.LogUtil;
import com.huawei.ailife.service.kit.callback.DataCallback;
import com.huawei.ailife.service.kit.model.CommandParam;
import com.huawei.ailife.service.kit.model.HiLinkDevice;

import com.chinasoftinc.facommon.DeviceControlConstants;
import com.chinasoftinc.facommon.utils.Optional2;


/**
 * @since 2022-04-20
 */
public abstract class Conversation implements DataCallback<String> {
    private static final String TAG = "Conversation";
    protected HiLinkDevice hiLinkDevice;
    protected Optional2<HiLinkDataCallback> dataChangeCallback = Optional2.empty();

    public Conversation() {
    }

    public void setHiLinkDataCallback(HiLinkDataCallback callback) {
        this.dataChangeCallback = Optional2.ofNullable(callback);
    }

    public void withHiLinkDevice(HiLinkDevice device) {
        this.hiLinkDevice = device;
    }

    public abstract void connect();

    public abstract void disconnect();

    public void sendCommand(CommandParam command) {
        hiLinkDevice.sendCommand(command, this);
    }

    @Override
    public void onSuccess(String message) {
        LogUtil.info(TAG, "sendCommand onSuccess: " + message);
        dataChangeCallback
            .ifPresent(hiLinkDataCallback -> hiLinkDataCallback.onSuccess(DeviceControlConstants.SEND_COMMAND, message))
            .noPresent(WarnLog.INSTANCE);
    }

    @Override
    public void onFailure(int errorCode, String message) {
        LogUtil.info(TAG, "sendCommand onFailure: errorCode = " + errorCode + " message = "+message);
        dataChangeCallback
            .ifPresent(hiLinkDataCallback -> hiLinkDataCallback.onFail(DeviceControlConstants.SEND_COMMAND, errorCode, message))
            .noPresent(WarnLog.INSTANCE);
    }

    public abstract void init();

    public void onDeviceIdChange() {
    }
}
